package org.shellex.javame.utility;

import javax.microedition.rms.*;


public class StoreManager {
	static StoreManager instance;
	
	private StoreManager(){};
	
	public static StoreManager getInstance()
	{
		if(instance == null)
			instance = new StoreManager();
		return instance;
	} 
	
	/**
	 * @param name
	 * @return true if specified record exist, or false
	 */
	public boolean exist(String name) {
		try {
			RecordStore r = RecordStore.openRecordStore(name, false);
			r.closeRecordStore();
			r=null;
			return true;
		}catch (RecordStoreException e) {
			System.out.println(e.getMessage());
			return false;
		}
	}
	
	/**
	 * @param name, A name assign to the new record. 
	 * @return null if create fail, or a new RecordStore object
	 * @throws StoreManagerException if specified record exist
	 */
	public RecordStore create(String name){
		RecordStore r = null;
		try {
			r = RecordStore.openRecordStore(name, true);
			r.closeRecordStore();
			r = null;
		} catch (RecordStoreException e) {
			System.err.println(e.getMessage());
			return null; 
		}
		return r;	
	}
	
	public boolean remove(String name) {
		try {
			RecordStore.deleteRecordStore(name);
		} catch (RecordStoreException e)  {
			return false;
		}
		return true;
	}
	
	public RecordStore open(String name) {
		RecordStore r = null;
		try {
			r = RecordStore.openRecordStore(name, false);
		} catch (RecordStoreException e) {
			return null;
		}
		return r;
	}
	public boolean close(RecordStore r) {
		if (r != null) {
			try {
				r.closeRecordStore();
				r = null;
				return true;
			}catch (RecordStoreException e) {
				return false;
			}
		}
		return false;
	}
	
}
